package com.li.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.li.domain.Employee;
import com.li.domain.EmployeeRole;
import com.li.domain.Role;
import com.li.service.AdminRoleService;
import com.li.service.EmployeeRoleService;
import com.li.service.EmployeeService;
import com.li.utlis.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeRoleService employeeRoleService;

    @RequestMapping("/listEmp")
    public JSONObject listEmp(Employee employee,Integer page,Integer limit){
        List<Employee> list=employeeService.listPage(employee,page,limit);
        Integer count=employeeService.listPageCount(employee);
        return R.listPage(list,count);
    }

    @RequestMapping("/saveOrUpdateEmp")
    public JSONObject saveOrUpdateEmp(Employee employee){
        if (employee==null || employee.getUsername()==null){
            return R.getError(employee);
        }
        if (employee.getId()!=null && !"".equals(employee.getId())){
            //修改
            try {
                employeeService.updateEmp(employee);
            }catch (Exception e){
                return R.getError(employee);
            }
        }else{
            //添加
            try {
                employeeService.addEmp(employee);
            }catch (Exception e){
                return R.getError(employee);
            }
        }
        return R.getSuccess();
    }

    @RequestMapping("/delEmp")
    public JSONObject delEmp(Employee employee){
        employeeService.delEmp(employee);
        return R.getSuccess();
    }

    @RequestMapping("/editRoleByIdEmp")
    public List<EmployeeRole> editRoleByIdEmp(Employee employee){
        return employeeRoleService.list(new QueryWrapper<EmployeeRole>().eq("employee_id",employee.getId()));
    }

    /**
     * 头像上传
     * @param uploadFile
     * @param req
     * @return
     */
    @RequestMapping("/uploadAvatar")
    public String uploadAvatar(MultipartFile uploadFile, HttpServletRequest req){
        String path=null;
        try {
            path=employeeRoleService.uploadAvatar(uploadFile , req);
        }catch (Exception e){
            return null;
        }
        return path;
    }
}
